<?php 
/***
    Amrita ITEWS - Copyright (C) 2009 Amrita Vishwa Vidyapeetham, Amritapuri.
                                     (http://www.amrita.edu)
    ***************************************************************************
    This file is part of the Amrita ITEWS distribution.
    Amrita ITEWS is free software; you can redistribute it and/or modify it 
    under the terms of the GNU General Public License (version 2) as published 
    by the Free Software Foundation AND MODIFIED BY the Amrita ITEWS exception.
    ***NOTE*** The exception to the GPL is included to allow you to distribute
    a combined work that includes Amrita ITEWS without being obliged to provide
    the source code for proprietary components outside of the Amrita ITEWS
    software. Amrita ITEWS is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
    Public License for more details. You should have received a copy of the GNU
    General Public License and the Amrita ITEWS license exception along with 
    Amrita ITEWS if not then it can be viewed here: 
    http://itews.amrita.ac.in/license.html.
    
    Documentation, latest information, license and contact details are at:
    http://itews.amrita.ac.in/
 
    Amrita ITEWS source code can be found at:
    http://code.google.com/p/itews"; 
    
    The initial code-base of Amrita ITEWS was developed by Amrita Vishwa 
    Vidyapeetham as part of the project titled,\"Intelligent & Interactive 
    Telematics using Emerging Wireless Technologies for Transport Systems 
    (ITEWS)\" sponsored by Technology Information Forecasting and Assessment 
    Council (TIFAC), India.
***/
?><?php
class PointOfInterestsController extends AppController {

	var $name = 'PointOfInterests';
	var $uses = array('PointOfInterest', 'PointOfInterestInfo', 'PointOfInterestCode');

	function index() {
		
		list($order, $limit, $page) = $this->setupPagination();
		$this->set('pointOfInterests', $this->PointOfInterest->findAll(NULL, NULL, $order, $limit, $page));
		
	}

	function view($id = null) {
		
		$this->checkRecordExistance($id);
		$this->set('pointOfInterest', $this->PointOfInterest->read(null, $id));
		
	}

	function add() {
		if (empty($this->data)) {
			$this->render();
		} else {
			$this->cleanupData();
			$this->data['PointOfInterest']['point_of_interest_code'] = low($this->data['PointOfInterest']['point_of_interest_code']);
			if ($this->data['PointOfInterest']['point_of_interest_latitude_direction'] == 'N') {
				$this->data['PointOfInterest']['point_of_interest_latitude'] =  ($this->data['PointOfInterest']['point_of_interest_latitude']) ? '+' . $this->data['PointOfInterest']['point_of_interest_latitude'] : "";
			} else if ($this->data['PointOfInterest']['point_of_interest_latitude_direction'] == 'S') {
				$this->data['PointOfInterest']['point_of_interest_latitude'] =  ($this->data['PointOfInterest']['point_of_interest_latitude']) ? '-' . $this->data['PointOfInterest']['point_of_interest_latitude'] : "";
				 
			}
			if ($this->data['PointOfInterest']['point_of_interest_longitude_direction'] == 'E') {
				$this->data['PointOfInterest']['point_of_interest_longitude'] =  ($this->data['PointOfInterest']['point_of_interest_longitude']) ? '+' . $this->data['PointOfInterest']['point_of_interest_longitude'] : "";
			} else if ($this->data['PointOfInterest']['point_of_interest_longitude_direction'] == 'W') {
				$this->data['PointOfInterest']['point_of_interest_longitude'] =  ($this->data['PointOfInterest']['point_of_interest_longitude']) ? '-' . $this->data['PointOfInterest']['point_of_interest_longitude'] : "";
				 
			}
			$this->PointOfInterest->begin();
			$this->PointOfInterestCode->begin();
			$this->PointOfInterestInfo->begin();
			$allowCommit = true;
			if ($this->PointOfInterest->save($this->data)) {
				$poiId = $this->PointOfInterest->getLastInsertID();
				$poiCodeFields['PointOfInterestCode.point_of_interest_code'] = $this->data['PointOfInterest']['point_of_interest_code'];
				if (!$this->PointOfInterestCode->hasAny($poiCodeFields)) {
					$poiCodeData['PointOfInterestCode']['point_of_interest_id'] = $poiId;
					$poiCodeData['PointOfInterestCode']['point_of_interest_code'] = $this->data['PointOfInterest']['point_of_interest_code'];
					if (!$this->PointOfInterestCode->save($poiCodeData)) {
						$allowCommit = false;
						$this->Session->setFlash('Error while updating poi code list.', 'message_error');
					}
				} else {
					$allowCommit = false;
					$this->Session->setFlash('Code already exists in Point of Interest codes list.', 'message_error');
				}
				if (!$this->pushToPoiInfoQueue('poi', $poiId)) {
					$allowCommit = false;
					$this->Session->setFlash('Error while updating POI info table.', 'message_error');
				}
			} else {
					$allowCommit = false;
				$this->Session->setFlash('Please correct errors below.', 'message_error');
			}
			if ($allowCommit) {
				$this->PointOfInterest->commit();
				$this->PointOfInterestCode->commit();
				$this->PointOfInterestInfo->commit();
				$this->Session->setFlash('The Point of Interest has been added.', 'message_ok');
				$this->redirect('/point_of_interests/index');
			} else {
				$this->PointOfInterest->rollback();
				$this->PointOfInterestCode->rollback();
				$this->PointOfInterestInfo->rollback();
			}
		}
	}

	function edit($id = null) {
		if (empty($this->data)) {
			$this->checkRecordExistance($id);
			$this->data = $this->PointOfInterest->read(null, $id);
		} else {
			$this->cleanupData();
			$this->data['PointOfInterest']['point_of_interest_code'] = low($this->data['PointOfInterest']['point_of_interest_code']);
			$this->data['PointOfInterest']['point_of_interest_code'] = low($this->data['PointOfInterest']['point_of_interest_code']);
			if ($this->data['PointOfInterest']['point_of_interest_latitude_direction'] == 'N') {
				$this->data['PointOfInterest']['point_of_interest_latitude'] =  ($this->data['PointOfInterest']['point_of_interest_latitude']) ? '+' . $this->data['PointOfInterest']['point_of_interest_latitude'] : "";
			} else if ($this->data['PointOfInterest']['point_of_interest_latitude_direction'] == 'S') {
				$this->data['PointOfInterest']['point_of_interest_latitude'] =  ($this->data['PointOfInterest']['point_of_interest_latitude']) ? '-' . $this->data['PointOfInterest']['point_of_interest_latitude'] : "";
				 
			}
			if ($this->data['PointOfInterest']['point_of_interest_longitude_direction'] == 'E') {
				$this->data['PointOfInterest']['point_of_interest_longitude'] =  ($this->data['PointOfInterest']['point_of_interest_longitude']) ? '+' . $this->data['PointOfInterest']['point_of_interest_longitude'] : "";
			} else if ($this->data['PointOfInterest']['point_of_interest_longitude_direction'] == 'W') {
				$this->data['PointOfInterest']['point_of_interest_longitude'] =  ($this->data['PointOfInterest']['point_of_interest_longitude']) ? '-' . $this->data['PointOfInterest']['point_of_interest_longitude'] : "";
				 
			}
			$this->PointOfInterest->begin();
			$this->PointOfInterestInfo->begin();
			if ($this->PointOfInterest->save($this->data)) {
				if ($this->pushToPoiInfoQueue('poi', $id)) {
					$this->PointOfInterest->commit();
					$this->PointOfInterestInfo->commit();
					$this->Session->setFlash('The Point of Interest has been saved.', 'message_ok');
					$this->redirect('/point_of_interests/index');
				} else {
					$this->PointOfInterest->rollback();
					$this->PointOfInterestInfo->rollback();
					$this->Session->setFlash('Error while upadatig POI info queue.', 'message_error');
				}
			} else {
				$this->PointOfInterest->rollback();
				$this->PointOfInterestInfo->rollback();
				$this->Session->setFlash('Please correct errors below.', 'message_error');
			}
		}
	}

	function delete($id = null) {
		
		$this->checkRecordExistance($id);
		$this->PointOfInterest->begin();
		$this->PointOfInterestCode->begin();
		$this->PointOfInterestInfo->begin();
		$allowCommit = true;
		if ($this->PointOfInterest->del($id)) {
			if (!$this->refreshPoiInfoQueue($id)) {
				$allowCommit = false;
				$this->Session->setFlash('Error while updating POI Infos queue, Point of Interest not deleted.', 'message_error');
			}
			$poiCodeListEntry = $this->PointOfInterestCode->find(array("PointOfInterestCode.point_of_interest_id" => $id));
			$poiCodeListEntry ['PointOfInterestCode']['point_of_interest_deleted'] = 1;
			if (!$this->PointOfInterestCode->save($poiCodeListEntry )) {
				$allowCommit = false;
				$this->Session->setFlash('Error while updating points of interest code list, Point of interest not deleted.', 'message_error');
			}
			if ($allowCommit) {
				$this->PointOfInterest->commit();
				$this->PointOfInterestInfo->commit();
				$this->PointOfInterestCode->commit();
				$this->Session->setFlash('The Point of Interest deleted.', 'message_ok');
				$this->redirect('/point_of_interests/index');
			} else {
				$this->PointOfInterest->rollback();
				$this->PointOfInterestInfo->rollback();
				$this->PointOfInterestCode->rollback();
				$this->redirect('/point_of_interests/index');
			}
		} else {
			$this->PointOfInterest->rollback();
			$this->PointOfInterestInfo->rollback();
			$this->PointOfInterestCode->rollback();
			$this->showError(ERROR_DELETE, 'Unable to delete record.');
		}
		
	}
	
	function view_multiple($id = null) {
		$flag = true;
		if (isset($this->params['url']['ids'])) {
			$ids = explode(";", $this->params['url']['ids']);
			if (count($ids) > 0) {
				foreach ($ids as $id) {
					if ($id != null) {
						$id = intval($id); 
						unset($fields);
						$fields['PointOfInterest.id'] = $id;
						if ($this->PointOfInterest->hasAny($fields)) {
							$validIds[] = $id; 
						}
					} 
				}
				if (isset($validIds)) {
					$idList           = implode(",", $validIds);
					$conditions       = array("PointOfInterest.id IN ($idList)");
					$pointOfInterests = $this->PointOfInterest->findAll($conditions);
				} else {
					$flag = false;
				}
			} else {
				$flag = false;
			}
		} else {
			$flag = false;
		}
		if ($flag) {
			$this->set('pointOfInterests', $pointOfInterests);
		} else {
			$this->Session->setFlash('No Points of Interest selected to view.', 'message_error');
			$this->redirect('/point_of_interests/index');
		}
	}
	
	/**
	 * Pushes a new entry to the poi info queue 
	 * Do nothing if an entry with same info type and reference already exists
	 */
	function pushToPoiInfoQueue($infoType, $referenceId) {
		
		$fields['point_of_interest_info_type']      = $infoType; 
		$fields['point_of_interest_info_reference'] = $referenceId;
		if ($this->PointOfInterestInfo->hasAny($fields)) {
			// Entry already exists; Just return
			return true;
		}
		$data['PointOfInterestInfo']['id']                               = null;
		$data['PointOfInterestInfo']['point_of_interest_info_type']      = $infoType;
		$data['PointOfInterestInfo']['point_of_interest_info_reference'] = $referenceId;
		if ($this->PointOfInterestInfo->save($data)) {
			return true;
		} else {
			return false;
		}
		 
	}
	
	function refreshPoiInfoQueue($id) {
		
		$fields['PointOfInterestInfo.point_of_interest_info_reference'] = $id;
		if ($this->PointOfInterestInfo->hasAny($fields)) {
			$poiInfoId = $this->PointOfInterestInfo->field('PointOfInterestInfo.id', $fields);
			return $this->PointOfInterestInfo->del($poiInfoId);
		} else {
			return $this->pushToPoiInfoQueue('poi', $id);
		}
		
	}

}
?>